import React, {useState} from 'react';
import {ChevronDown, ChevronRight, X} from 'lucide-react';

interface Permission {
    id: string;
    name: string;
    description: string;
    group: string;
}

interface Role {
    id: number;
    name: string;
    remark: string;
    permissions: string[];
}

interface RoleManageModalProps {
    mode: 'add' | 'edit';
    role?: Role;
    permissions: Permission[];
    onClose: () => void;
    onSave: (data: any) => void;
}

export default function RoleManageModal({
                                            mode,
                                            role,
                                            permissions,
                                            onClose,
                                            onSave
                                        }: RoleManageModalProps) {
    const [formData, setFormData] = useState({
        id: role?.id || '',
        name: role?.name || '',
        remark: role?.remark || '',
        permissions: role?.permissions || []
    });

    const [expandedGroups, setExpandedGroups] = useState<string[]>(
        Array.from(new Set(permissions.map(p => p.group)))
    );

    // 按组分类权限
    const permissionGroups = permissions.reduce((groups, permission) => {
        const group = permission.group;
        if (!groups[group]) {
            groups[group] = [];
        }
        groups[group].push(permission);
        return groups;
    }, {} as Record<string, Permission[]>);

    const toggleGroup = (group: string) => {
        setExpandedGroups(prev =>
            prev.includes(group)
                ? prev.filter(g => g !== group)
                : [...prev, group]
        );
    };

    const togglePermission = (permissionId: string) => {
        setFormData(prev => ({
            ...prev,
            permissions: prev.permissions.includes(permissionId)
                ? prev.permissions.filter(id => id !== permissionId)
                : [...prev.permissions, permissionId]
        }));
    };

    const toggleGroupPermissions = (group: string, groupPermissions: Permission[]) => {
        const permissionIds = groupPermissions.map(p => p.id);
        const allSelected = groupPermissions.every(p => formData.permissions.includes(p.id));

        setFormData(prev => ({
            ...prev,
            permissions: allSelected
                ? prev.permissions.filter(id => !permissionIds.includes(id))
                : [...new Set([...prev.permissions, ...permissionIds])]
        }));
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        onSave(formData);
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-2xl mx-4">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">
                        {mode === 'add' ? '添加角色' : '编辑角色'}
                    </h3>
                    <button onClick={onClose}>
                        <X className="w-6 h-6 text-gray-500"/>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6">
                    <div className="space-y-6">
                        {/* 基本信息 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                角色名称 <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={formData.name}
                                onChange={(e) => setFormData({...formData, name: e.target.value})}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                required
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                角色描述
                            </label>
                            <input
                                type="text"
                                value={formData.remark}
                                onChange={(e) => setFormData({...formData, remark: e.target.value})}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                        </div>

                        {/* 权限设置 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                权限设置
                            </label>
                            <div className="border rounded-lg divide-y max-h-96 overflow-y-auto">
                                {Object.entries(permissionGroups).map(([group, groupPermissions]) => (
                                    <div key={group} className="bg-white">
                                        <button
                                            type="button"
                                            onClick={() => toggleGroup(group)}
                                            className="w-full flex items-center justify-between p-3 hover:bg-gray-50"
                                        >
                                            <div className="flex items-center">
                                                {expandedGroups.includes(group) ? (
                                                    <ChevronDown className="w-5 h-5 text-gray-400"/>
                                                ) : (
                                                    <ChevronRight className="w-5 h-5 text-gray-400"/>
                                                )}
                                                <span className="ml-2 font-medium text-gray-900">{group}</span>
                                            </div>
                                            <label className="flex items-center">
                                                <input
                                                    type="checkbox"
                                                    checked={groupPermissions.every(p => formData.permissions.includes(p.id))}
                                                    onChange={() => toggleGroupPermissions(group, groupPermissions)}
                                                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                                />
                                            </label>
                                        </button>
                                        {expandedGroups.includes(group) && (
                                            <div className="pl-10 pr-3 pb-3 space-y-3">
                                                {groupPermissions.map(permission => (
                                                    <div key={permission.id}
                                                         className="flex items-center justify-between">
                                                        <div>
                                                            <div className="text-sm font-medium text-gray-900">
                                                                {permission.name}
                                                            </div>
                                                            <div className="text-sm text-gray-500">
                                                                {permission.description}
                                                            </div>
                                                        </div>
                                                        <label className="flex items-center">
                                                            <input
                                                                type="checkbox"
                                                                checked={formData.permissions.includes(permission.id)}
                                                                onChange={() => togglePermission(permission.id)}
                                                                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                                                            />
                                                        </label>
                                                    </div>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    <div className="flex justify-end space-x-3 mt-6">
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                        >
                            取消
                        </button>
                        <button
                            type="submit"
                            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                        >
                            确定
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}